package loggers

import (
	"context"
	"github.com/opentracing/opentracing-go"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

// 简单日志实例
var simpleLogger *zap.Logger

var errorLogger *zap.Logger

var appName string

func init() {
	simpleLogger = NewLogger("", "", zapcore.InfoLevel, MODE_CONSOLE)
	errorLogger = NewLogger("", "", zapcore.ErrorLevel, MODE_CONSOLE)
}

// 注册实例到简单日志
func RegisterSimpleLogger(logger *zap.Logger) {
	simpleLogger = logger
}

// 注册实例到异常日志
func RegisterErrorLogger(logger *zap.Logger) {
	errorLogger = logger
}

// 设置应用名称
func SetAppName(name string) {
	appName = name
}

func AppendFields(ctx context.Context, fields ...zapcore.Field) []zapcore.Field {
	// 获取链路中的信息
	if ctx != nil {
		sp := opentracing.SpanFromContext(ctx)
		if sp != nil {
			textMap := opentracing.TextMapCarrier{}
			err := opentracing.GlobalTracer().Inject(sp.Context(), opentracing.TextMap, textMap)
			if err == nil {
				for k, v := range textMap {
					fields = append(fields, zap.String(k, v))
				}
			}
		}
	}
	// 获取应用名称
	fields = append(fields, zap.String("app", appName))
	return fields

}

func Info(mgs string, ctx context.Context, fields ...zapcore.Field) {
	simpleLogger.Info(mgs, AppendFields(ctx, fields...)...)
}

func Debug(mgs string, ctx context.Context, fields ...zapcore.Field) {
	simpleLogger.Debug(mgs, AppendFields(ctx, fields...)...)
}

func Warn(mgs string, ctx context.Context, fields ...zapcore.Field) {
	simpleLogger.Warn(mgs, AppendFields(ctx, fields...)...)
}

func Error(mgs string, ctx context.Context, fields ...zapcore.Field) {
	errorLogger.Error(mgs, AppendFields(ctx, fields...)...)
}

func Fatal(mgs string, ctx context.Context, fields ...zapcore.Field) {
	simpleLogger.Fatal(mgs, AppendFields(ctx, fields...)...)
}
